#!/usr/bin/env node

/**
 * MUI Grid 兼容性检查脚本
 * 检测项目中可能存在的 Grid 组件兼容性问题
 */

const fs = require('fs');
const path = require('path');

// 需要检查的文件扩展名
const EXTENSIONS = ['.tsx', '.jsx', '.ts', '.js'];

// 需要检查的目录
const CHECK_DIRS = ['src'];

// 问题模式
const PATTERNS = [
  {
    name: 'Grid导入',
    pattern: /import.*{[^}]*Grid[^}]*}.*from.*@mui\/material/g,
    severity: 'warning',
    description: '检测到Grid组件导入，可能存在兼容性问题'
  },
  {
    name: 'Grid container属性',
    pattern: /<Grid[^>]*container[^>]*>/g,
    severity: 'error',
    description: 'Grid container属性在MUI v7中不兼容'
  },
  {
    name: 'Grid item属性',
    pattern: /<Grid[^>]*item[^>]*>/g,
    severity: 'error',
    description: 'Grid item属性在MUI v7中不兼容'
  },
  {
    name: 'Grid响应式属性',
    pattern: /<Grid[^>]*(xs|sm|md|lg|xl)=\{[^}]+\}/g,
    severity: 'error',
    description: 'Grid响应式属性写法在MUI v7中已改变'
  }
];

/**
 * 递归获取所有需要检查的文件
 */
function getAllFiles(dir, fileList = []) {
  const files = fs.readdirSync(dir);
  
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory()) {
      // 跳过 node_modules 和 build 目录
      if (!['node_modules', 'build', 'dist', '.git'].includes(file)) {
        getAllFiles(filePath, fileList);
      }
    } else if (EXTENSIONS.some(ext => file.endsWith(ext))) {
      fileList.push(filePath);
    }
  });
  
  return fileList;
}

/**
 * 检查单个文件
 */
function checkFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf-8');
  const issues = [];
  
  PATTERNS.forEach(pattern => {
    let match;
    while ((match = pattern.pattern.exec(content)) !== null) {
      const lines = content.substring(0, match.index).split('\n');
      const lineNumber = lines.length;
      const lineContent = lines[lineNumber - 1].trim();
      
      issues.push({
        file: filePath,
        line: lineNumber,
        pattern: pattern.name,
        severity: pattern.severity,
        description: pattern.description,
        content: lineContent,
        match: match[0]
      });
    }
    // 重置正则表达式的 lastIndex
    pattern.pattern.lastIndex = 0;
  });
  
  return issues;
}

/**
 * 主函数
 */
function main() {
  console.log('🔍 开始检查 MUI Grid 兼容性问题...\n');
  
  let totalIssues = 0;
  let errorCount = 0;
  let warningCount = 0;
  
  CHECK_DIRS.forEach(dir => {
    if (!fs.existsSync(dir)) {
      console.log(`⚠️  目录 ${dir} 不存在，跳过检查`);
      return;
    }
    
    const files = getAllFiles(dir);
    console.log(`📁 检查目录: ${dir} (${files.length} 个文件)`);
    
    files.forEach(file => {
      const issues = checkFile(file);
      
      if (issues.length > 0) {
        console.log(`\n📄 ${file}:`);
        
        issues.forEach(issue => {
          const icon = issue.severity === 'error' ? '❌' : '⚠️';
          console.log(`  ${icon} 第${issue.line}行: ${issue.description}`);
          console.log(`     代码: ${issue.content}`);
          console.log(`     匹配: ${issue.match}`);
          
          totalIssues++;
          if (issue.severity === 'error') {
            errorCount++;
          } else {
            warningCount++;
          }
        });
      }
    });
  });
  
  console.log('\n' + '='.repeat(60));
  console.log(`🎯 检查完成！`);
  console.log(`📊 总问题数: ${totalIssues}`);
  console.log(`❌ 错误: ${errorCount}`);
  console.log(`⚠️  警告: ${warningCount}`);
  
  if (totalIssues === 0) {
    console.log('✅ 恭喜！没有发现 Grid 兼容性问题。');
  } else {
    console.log('\n📖 修复建议:');
    console.log('1. 参考 TROUBLESHOOTING.md 文档');
    console.log('2. 使用 Box + CSS Grid/Flexbox 替代 Grid 组件');
    console.log('3. 运行 npm run build 验证修复结果');
  }
  
  // 如果有错误，退出码为1
  process.exit(errorCount > 0 ? 1 : 0);
}

if (require.main === module) {
  main();
}

module.exports = { checkFile, getAllFiles, PATTERNS };
